﻿using CardMonitor.Utils;
using LibVLCSharp.Shared;
using LocalServer.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WeighClient.Model;
using WeighClient.Utils;

namespace WeighClient.Windows
{
    /// <summary>
    /// IndexWindow.xaml 的交互逻辑
    /// </summary>
    public partial class IndexWindow : Window
    {
        private Thread readCardThread = null;
        private Block block = null;

        private delegate void MyDelegate(Object value);

        private SynchronizationContext _syncContext = null;
        private static string ledIp = "";
        private SaleInfoWindow saleInfoWindow;
        private PurchaseInfoWindow purchaseInfoWindow;
        private Bill Bill;
        private int m_iInit1 = -1;

        //int m_iStatus1 = -1;
        private int m_iInit2 = -1;

        //int m_iStatus2 = -1;

        public IndexWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            this.Loaded += Window_Load;
            this.Unloaded += Window_UnLoad;
            CommonInterface.PortType = "USB";
            CommonInterface.PortPara = "0400C35A";
            CommonInterface.ExtendPara = "";
            //Bill = new Bill();
            //Bill.busitype = "鲁E12345";
            //SaleInfoWindow saleInfoWindow = new SaleInfoWindow(Bill, "", "");
            //saleInfoWindow.Show();

            /* VlcWindow vlcWindow = new VlcWindow();
             vlcWindow.Show();*/
        }

        /// <summary>
        /// 软件关闭
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e">      </param>
        private void Window_UnLoad(object sender, RoutedEventArgs e)
        {
            coseCardReader();
        }

        /// <summary>
        /// 软件初始化
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e">      </param>
        private void Window_Load(object sender, RoutedEventArgs e)
        {
            try
            {
                HttpServer server = App.GetHttpServer();
                if (null != server)
                {
                    HttpServer.sendMsgEvent += Server_sendMsgEvent;
                }
            }
            catch (Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Error");
                MessageBox.Show(ex.ToString());
            }

            if (App.GetConfig().IfPrint.Equals("0"))
            {
            }
            cardReaderInitialization();
        }

        private void Server_sendMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(d, obj);
        }

        private void DealMessage(Object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");
            String direction = (String)jsonObj.GetValue("direction");
            string printer1 = App.GetConfig().Printer01;
            string printer2 = App.GetConfig().Printer02;

            if ("LoadBillInfo".Equals(type))
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                //string IpImagePath = App.GetConfig().IpImagePath;
                string ImagePath1 = (string)detailJSON.GetValue("img1");
                string ImagePath2 = (string)detailJSON.GetValue("img2");

                //_syncContext.Post(AddLogTxt, detailObj.ToString());
                Bill = Json2Bill(detailJSON);
                OpenFreshWindowForBill(Bill, ImagePath1, ImagePath2);
            }
            else if ("openDevice".Equals(type))
            {
                int code = NewIDcardread.Opendevice();
                if (code != 1)
                {
                    MessageBox.Show("身份证读卡器打开失败");
                }
            }
            else if ("closeIdDevice".Equals(type))
            {
                int code = NewIDcardread.closeID();

                if (code != 0)
                {
                    MessageBox.Show("读卡器关闭失败");
                }
            }
            else if ("readCardNo".Equals(type))
            {
                string facId = "";
                string driverMacCard = "";
                IDCardInfo iDCardInfo = null;
                if ("1".Equals(App.GetConfig().IDCard))//身份证读卡器读卡
                {
                    string cardReader = App.GetConfig().cardReader;

                    if ("1".Equals(cardReader))//精伦读卡器
                    {
                        NewIDcardread.CardAuthentication();
                        NewCardInfo newCardInfo = NewIDcardread.ReadIDcard();
                        if (newCardInfo != null)
                        {
                            facId = newCardInfo.CardNo;
                            driverMacCard = newCardInfo.driverMacCard;
                        }
                        else
                        {
                            return;
                        }
                    }
                    else if ("2".Equals(cardReader)) //熵机
                    {
                        iDCardInfo = IDCardReaderUtil_Sjdll.ReadCard();
                        if (iDCardInfo.IDNumber != "" & iDCardInfo.IDNumber != null)
                        {
                            facId = iDCardInfo.IDNumber;
                            driverMacCard = iDCardInfo.MacCard;
                        }
                    }
                }
                else
                {
                    facId = App.GetConfig().cardReader;
                    driverMacCard = App.GetConfig().driverMacCard;
                }

                if (facId != "" || facId != null)
                {
                    JObject cardNoJson = new JObject();
                    cardNoJson.Add("facCardNo", facId);
                    cardNoJson.Add("driverMacCard", driverMacCard);
                    SendMessageUtils.SendNodeRedMsg("PostMessage/facCardNo", cardNoJson);
                }
            }
            else if ("UploadBillSuccess".Equals(type))
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                Bill = Json2Bill(detailJSON);

                if (App.GetConfig().IfPrint.Equals("0"))
                {
                    if (Bill.print == "1")
                    {
                        PrintUtils.printWeighOrder(Bill);
                    }
                }
            }
            else if ("ErrorMessage".Equals(type))
            {
                string errorMsg = (string)jsonObj.GetValue("msg");
                if (saleInfoWindow != null)
                {
                    saleInfoWindow.LabelMsg(errorMsg);//报警信息
                }
                if (purchaseInfoWindow != null)
                {
                    purchaseInfoWindow.LabelMsg(errorMsg);
                }
            }
            else if ("UpdateBill".Equals(type))//更新数据
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                Bill = Json2Bill(detailJSON);
                //Bill bill = new Bill();
                if ("销售".Equals(Bill.busitype) || "租赁销售".Equals(Bill.busitype))
                {
                    saleInfoWindow.UpdateBill(Bill);
                }
                else
                {
                    purchaseInfoWindow.UpdateBill(Bill);
                }
            }
            else if ("Complete".Equals(type))
            {
                CloseInfoWindowsHard();
            }
            else if ("PrintSmallTicket".Equals(type))
            {
                Console.WriteLine("PrintSmallTicket...");

                JObject billObj = (JObject)jsonObj.GetValue("billObj");
                Bill bill = Json2Bill(billObj);

                PrintUtils.printWeighOrder(bill);
            }
        }

        private Bill Json2Bill(JObject detailJSON)
        {
            String id = (String)detailJSON.GetValue("id");
            String orderCode = (String)detailJSON.GetValue("billNo");
            String carNo = (String)detailJSON.GetValue("carNumber");
            String productName = (String)detailJSON.GetValue("productName");
            String corpName = (String)detailJSON.GetValue("companyName");
            String position = (String)detailJSON.GetValue("position");
            String planNum = (String)detailJSON.GetValue("planNum");
            String _guid = (String)detailJSON.GetValue("guid");
            String weigh = (String)detailJSON.GetValue("weigh");
            String personWeigh01 = (String)detailJSON.GetValue("personWeight01");
            String personWeigh02 = (String)detailJSON.GetValue("personWeight02");
            String loadPlaceName = (String)detailJSON.GetValue("loadPlaceName");
            String materialName = (String)detailJSON.GetValue("materialName");
            String cpzTime = (String)detailJSON.GetValue("cpzTime");
            String cmzTime = (String)detailJSON.GetValue("cmzTime");
            String price = (String)detailJSON.GetValue("price");
            String customerName = (String)detailJSON.GetValue("corpName");
            String fnpolicemsg = (String)detailJSON.GetValue("fnpolicemsg");
            Bill bill = new Bill();

            bill.id = id;
            bill.orderCode = orderCode;
            bill.carNo = carNo;
            bill.productName = productName;
            bill.corpName = corpName;
            bill.position = position;
            bill.planNum = planNum;
            bill.videoCarNo = App.GetRunTimeVariable().CarNo;
            bill.personWeight01 = personWeigh01;
            bill.personWeight02 = personWeigh02;
            bill.loadPlace = loadPlaceName;
            bill.cpzTime = cpzTime;
            bill.cmzTime = cmzTime;
            bill.price = price;
            bill.customerName = customerName;
            bill.qianbiao = (String)detailJSON.GetValue("fySurfaceFront");
            bill.lossNum = (String)detailJSON.GetValue("lossNum");
            bill.houbiao = (String)detailJSON.GetValue("fySurfaceBack");
            bill.fnpolicemsg = fnpolicemsg;
            bill.weightStatus = (String)detailJSON.GetValue("weightStatus");
            bill.yuanfaNum = (String)detailJSON.GetValue("yuanfaNum");
            bill.chazhi = (String)detailJSON.GetValue("chazhi");
            bill.fayou = (String)detailJSON.GetValue("fayou");
            bill.pizhong = (String)detailJSON.GetValue("pizhong");
            bill.maozhong = (String)detailJSON.GetValue("maozhong");
            bill.jingzhong = (String)detailJSON.GetValue("jingzhong");
            bill.qianbiao = (String)detailJSON.GetValue("qianbiao");
            bill.houbiao = (String)detailJSON.GetValue("houbiao");
            bill.busitype = (String)detailJSON.GetValue("busitype");
            bill.operatorName = (String)detailJSON.GetValue("operatorName");
            bill.print = (String)detailJSON.GetValue("print");
            bill.guid = _guid;
            bill.weigh = (String)detailJSON.GetValue("weigh");

            bill.materialName = materialName;

            return bill;
        }

        private void SendNodeRedMessage(String path, JObject reqObj)
        {
            try
            {
                String result = HttpPostHelper.doHttpPost(App.GetConfig().NodeRedUrl + path, reqObj.ToString());
            }
            catch (Exception ex) { }
        }

        private void CloseInfoWindowsHard()
        {
            lock (_uiLock)
            {
                // 确保在 UI 线程执行
                Application.Current.Dispatcher.Invoke((Action)(() =>
                {
                    // 1) 关闭有引用的实例
                    if (saleInfoWindow != null)
                    {
                        try { saleInfoWindow.Close(); } catch { }
                        saleInfoWindow = null;
                    }
                    if (purchaseInfoWindow != null)
                    {
                        try { purchaseInfoWindow.Close(); } catch { }
                        purchaseInfoWindow = null;
                    }

                    // 2) 兜底：清理所有遗留（无引用跟踪）的实例
                    for (int i = Application.Current.Windows.Count - 1; i >= 0; i--)
                    {
                        var w = Application.Current.Windows[i];
                        if (w is SaleInfoWindow || w is PurchaseInfoWindow)
                        {
                            try { w.Close(); } catch { }
                        }
                    }
                }));

                // 3) 让关闭消息先处理完，避免立即创建造成重影/未释放
                Application.Current.Dispatcher.Invoke((Action)(() => { }),
                    DispatcherPriority.Background);
            }
        }

        private readonly object _uiLock = new object();

        /// <summary>
        /// 清除页面
        /// </summary>
        /// <param name="bill"> </param>
        // ===== 严格的“先关后开（不复用旧窗口）” =====
        private void OpenFreshWindowForBill(Bill bill, String ImagePath1, String ImagePath2)
        {
            lock (_uiLock)
            {
                Application.Current.Dispatcher.Invoke((Action)(() =>
                {
                    // 先彻底清场
                    CloseInfoWindowsHard();

                    // 再创建全新实例（绝不复用）
                    if ("销售".Equals(bill.busitype) || "租赁销售".Equals(bill.busitype))
                    {
                        saleInfoWindow = new SaleInfoWindow(bill, ImagePath1, ImagePath2);
                        saleInfoWindow.Closed += (s, e) => { saleInfoWindow = null; };
                        saleInfoWindow.Show();
                        saleInfoWindow.Activate();
                    }
                    else
                    {
                        purchaseInfoWindow = new PurchaseInfoWindow(bill, ImagePath1, ImagePath2);
                        purchaseInfoWindow.Closed += (s, e) => { purchaseInfoWindow = null; };
                        purchaseInfoWindow.Show();
                        purchaseInfoWindow.Activate();
                    }
                }));
            }
        }

        /// <summary>
        /// 读卡器初始化
        /// </summary>
        private void cardReaderInitialization()
        {
            string cardReader = App.GetConfig().cardReader;

            if ("1".Equals(cardReader))//精伦读卡器
            {
                int code = NewIDcardread.Opendevice();
                if (code != 1)
                {
                    MessageBox.Show("精伦读卡器打开失败");
                }
            }
            else if ("2".Equals(cardReader)) //熵机
            {
                string IDCardPort = App.GetConfig().SJIDCardPort;
                int inport = Convert.ToInt32(IDCardPort);
                bool inPortType = IDCardReaderUtil_Sjdll.InitDevice(inport);
                if (!inPortType)
                {
                    MessageBox.Show("熵机读卡器设备打开失败");
                }
            }
        }

        /// <summary>
        /// 读卡器关闭
        /// </summary>
        private void coseCardReader()
        {
            string cardReader = App.GetConfig().cardReader;

            if ("1".Equals(cardReader))//精伦读卡器
            {
                if (m_iInit1 == 0)
                {
                    MsPrinterUtils.SetClose();
                }
            }
            else if ("2".Equals(cardReader)) //熵机
            {
                bool code = IDCardReaderUtil_Sjdll.CloseDevice();
                if (!code)
                {
                    MessageBox.Show("设备关闭失败");
                }
            }
        }
    }
}